//
// Created by root on 2/21/18.
//

#include "highlight.h"

HighlightBlock** get_highlight_blocks(gchar *text) {
    HighlightBlock** array = (HighlightBlock**) g_malloc(3 * sizeof(HighlightBlock*));
    if (g_str_equal(text, "{}")) {
        array[0] = (HighlightBlock*)g_malloc(sizeof(HighlightBlock));
        array[0]->start = 0;
        array[0]->end = 1;
        array[0]->fgColor = "#0080FF";
        array[0]->bgColor = "#FF8000";
        array[1] = (HighlightBlock*)g_malloc(sizeof(HighlightBlock));
        array[1]->start = 1;
        array[1]->end = 2;
        array[1]->fgColor = "#FF8000";
        array[1]->bgColor = "#0080FF";
        array[2] = NULL;
        return array;
    }
    return NULL;
}

GtkTextTagTable *table1;
GtkTextTag *highlight_tag;

void set_text_color(GtkTextBuffer *buffer, GtkTextIter *start, GtkTextIter *end, gchar *whichColor, gchar *color) {
    if(GTK_IS_TEXT_TAG_TABLE (table1))
        gtk_text_tag_table_remove(table1, highlight_tag);
    highlight_tag = gtk_text_buffer_create_tag(buffer, NULL, whichColor, color, NULL);
    if(GTK_IS_TEXT_TAG_TABLE (table1))
        gtk_text_tag_table_add(table1, highlight_tag);
    gtk_text_buffer_apply_tag(buffer, highlight_tag, start, end);
}

void set_foreground_color(GtkTextBuffer *buffer, GtkTextIter *start, GtkTextIter *end, gchar *color) {
    set_text_color(buffer, start, end, "foreground", color);
}

void set_background_color(GtkTextBuffer *buffer, GtkTextIter *start, GtkTextIter *end, gchar *color) {
    set_text_color(buffer, start, end, "background", color);
}

void highlight(GtkTextBuffer *buffer, FunnyWindow *app) {
    gchar *text = NULL;
    GtkTextIter start, end;
    gtk_text_buffer_get_bounds(buffer, &start, &end);
    text = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);

    gtk_text_buffer_remove_all_tags(buffer, &start, &end);

    GtkTextIter mstart, mend;
    HighlightBlock** blocks = get_highlight_blocks(text);
    if (!blocks) return;
    while (*blocks) {
        gtk_text_buffer_get_iter_at_offset(buffer, &mstart, (*blocks)->start);
        gtk_text_buffer_get_iter_at_offset(buffer, &mend, (*blocks)->end);
        set_foreground_color(buffer, &mstart, &mend, (*blocks)->fgColor);
        set_background_color(buffer, &mstart, &mend, (*blocks)->bgColor);
        blocks++;
    }
}

